package threadPool;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-12-20 11:36
 **/
public class T09_CachedThreadPool {


    public static void main(String[] args) throws InterruptedException {

        /**
         * =======>  Executors.newCachedThreadPool();
         * --------------------------------------------------------
         *     public static ExecutorService newCachedThreadPool() {
         *                                      // 弹性线程池，最小值为 0 ，最大值是 Integer.MAX_VALUE
         *                                      // 可以有很多线程，永远存活的为 0 ，
         *         return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
         *                                       60L, TimeUnit.SECONDS,
         *                                       // 注意这里使用的是 SynchronousQueue
         *
         *                                       new SynchronousQueue<Runnable>());
         */


        /***
         * CachedThreadPool 使用没有容量的 SynchronousQueue 作为阻塞队列；
         * 意味着，如果主线程提交任务的速度高于 maximumPool 中线程处理任务的速度时，CachedThreadPool 会不断创建新线程。
         * 极端情况下会创建过多的线程，耗尽 CPU 和内存资源
         */

        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            final int j = i;
            executorService.execute(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.err.println(Thread.currentThread().getName() + "-------------> " + j);
            });
        }

        System.err.println(executorService);
        Thread.sleep(2000);
        System.err.println(executorService);
        executorService.shutdown();

    }
}
